package com.kingyea.app.market.market.service.impl;

import com.alibaba.fastjson.JSON;
import com.kingyea.app.market.area.controller.AreaController;
import com.kingyea.app.market.condition.AllCondition;
import com.kingyea.app.market.market.bean.Market;
import com.kingyea.app.market.market.bean.MarketVo;
import com.kingyea.app.market.market.dao.MarketMapper;
import com.kingyea.app.market.market.service.MarketService;
import com.kingyea.app.market.marketorg.bean.MarketOrg;
import com.kingyea.app.market.marketorg.bean.MarketOrgPo;
import com.kingyea.app.market.marketorg.dao.MarketOrgMapper;
import com.kingyea.app.market.utils.ExceptionConditions;
import com.kingyea.app.market.utils.GlobalVar;
import com.kingyea.app.market.utils.StateCode;
import com.kingyea.app.market.utils.page.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @version v1.0.0
 * @description Market 实现类
 * @date Created in 2018-02-10 16:12:20
 */
@Service
@Transactional
public class MarketServiceImpl implements MarketService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MarketServiceImpl.class);

    @Resource
    private MarketMapper marketMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MarketOrgMapper marketOrgMapper;

    /**
     * 通过ID查找对象
     *
     * @param marketCode
     * @return
     */
    @Override
    public Market getById(String marketCode) throws Exception {
        Market market = marketMapper.getById(marketCode);
        return market;
    }

    @Override
    public List<Market> queryList(Map<String, Object> map) throws Exception {
        return marketMapper.queryList(map);
    }


    /**
     * 列表
     *
     * @param
     * @return
     */
    @Override
    public Object list(Map<String, Object> queryMarket) throws Exception {

        //行政区划code条件查询
        List<String> codeListParam = new ArrayList<>();
        if (queryMarket.containsKey("codeList") && !StringUtils.isEmpty(queryMarket.get("codeList"))) {
            codeListParam = JSON.parseObject(JSON.toJSONString(queryMarket.get("codeList")), List.class);
        }
        List<String> _codeList = new ArrayList<>();
        if (codeListParam.size() > 0) {
            for (int i = 0; i < codeListParam.size(); i++) {
                String _code = String.valueOf(codeListParam.get(i));
                if (_code.length() == 6) {
                    //是否选择了省
                    if (_code.substring(2, _code.length()).equals("0000"))
                        _codeList.add(_code.substring(0, 2));
                    else {
                        //是否选择了区/市
                        if (_code.substring(4, _code.length()).equals("00"))
                            _codeList.add(_code.substring(0, 4));
                            //是否选择了县/区
                        else
                            _codeList.add(_code);
                    }
                } else _codeList.add(_code);//是否选择街道
				/*List areaList1 = JSON.parseObject(String.valueOf(redisTemplate.opsForValue().get(AreaController.area_subset_prefix+_code)),List.class);
				if(areaList1!=null&&areaList1.size()>0){
					for (Object object : areaList1) {
						JSONObject parseObject = JSON.parseObject(object.toString());
						_codeList.add(parseObject.get("code").toString());
					}
				}*/
            }
        }
        queryMarket.remove("codeStr");
        queryMarket.put("codeList", _codeList);

        PageInfo.startPage(queryMarket);

        //根据code查出区域所有父级对象
        List<Object> marketList = marketMapper.list(queryMarket);
        for (int i = 0; i < marketList.size(); i++) {
            Market market = (Market) marketList.get(i);
            List areaLsit = JSON.parseObject(String.valueOf(redisTemplate.opsForValue().get(AreaController.area_details_prefix + market.getAdminArea())), List.class);
            if (null != areaLsit && areaLsit.size() > 0) {
                if (areaLsit.get(0).toString().contains("中国")) {
                    areaLsit.remove(0);
                }
            }
            market.setAdminArea(JSON.toJSONString(areaLsit));
        }

        return PageInfo.getPageInfo(marketList);
    }

    /**
     * 删除
     *
     * @param marketCode
     * @return
     */
    @Override
    public int deleteById(String marketCode) throws Exception {
        marketMapper.deleteById(marketCode);
        return 1;
    }

    /**
     * 保存
     *
     * @param market
     * @return
     */
    @Override
    public Object save(Map<String, Object> market) throws Exception {
        try {
            marketMapper.save(market);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return market;
    }

    /**
     * 更新
     *
     * @param market
     * @return
     */
    @Override
    public Object update(Map<String, Object> market) throws Exception {
        try {
            marketMapper.update(market);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return market;
    }

    @Override
    public List<Market> getMarketByUser(String loginAccount) throws Exception {
        // TODO Auto-generated method stub
        List<Market> marketList = marketMapper.getMarketByUser(loginAccount);
        for (Market market : marketList) {
            market.setAdminArea(String.valueOf(redisTemplate.opsForValue().get(AreaController.area_details_prefix + market.getAdminArea())));
        }
        return marketList;
    }

    @Override
    public Object getListBySupplier(Map<String, Object> obj) throws Exception {
        PageInfo.startPage(obj);
        //根据code查出区域所有父级对象
        List<MarketVo> marketList = marketMapper.getListBySupplier(obj);
        for (int i = 0; i < marketList.size(); i++) {
            MarketVo marketVo = marketList.get(i);
            List areaLsit = JSON.parseObject(String.valueOf(redisTemplate.opsForValue().get(AreaController.area_details_prefix + marketVo.getAdminArea())), List.class);
            if (null != areaLsit && areaLsit.size() > 0) {
                if (areaLsit.get(0).toString().contains("中国")) {
                    areaLsit.remove(0);
                }
            }
            marketVo.setAdminArea(JSON.toJSONString(areaLsit));
        }
        return PageInfo.getPageInfo(marketList);
    }

    @Override
    public List<MarketOrg> getMarketOrgList(AllCondition condition) {
        return marketOrgMapper.search(condition);
    }

    @Transactional
    @Override
    public Boolean batchSaveOrg(MarketOrgPo po) {
        ExceptionConditions.checkNotNull(po, StateCode.NO_ARGUMENT_ERROR);
        ExceptionConditions.checkNotNull(po.getMarketOrgs(), StateCode.NO_ARGUMENT_ERROR);
        ExceptionConditions.checkNotNull(po.getMarketCode(), StateCode.NO_ARGUMENT_ERROR);
        marketOrgMapper.deleteMarketCode(po.getMarketCode());
        if (!po.getMarketOrgs().isEmpty()) {
            po.getMarketOrgs().forEach(bean -> {
                bean.setMarketCode(po.getMarketCode());
                bean.setOrgParentSerialNo(po.getMarketOrgs().stream().anyMatch(bean2 -> bean.getOrgParentSerialNo().equals(bean2.getOrgSerialNo())) ? bean.getOrgParentSerialNo() : GlobalVar.TOP_LEVEL_ORGANIZATION);
            });
            return marketOrgMapper.batchSave(po.getMarketOrgs()) == po.getMarketOrgs().size();
        }
        return Boolean.TRUE;
    }
}
